const express = require('express')
const { param, query, validationResult } = require('express-validator')
const { query: dbQuery } = require('../config/database')
const { authenticateToken } = require('../middleware/auth')

const router = express.Router()

/**
 * @swagger
 * /api/bookshelf:
 *   get:
 *     summary: 获取用户书架
 *     tags: [书架]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 20
 *         description: 每页数量
 *     responses:
 *       200:
 *         description: 获取成功
 */
router.get(
  '/',
  [
    authenticateToken,
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit')
      .optional()
      .isInt({ min: 1, max: 100 })
      .withMessage('每页数量必须在1-100之间')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const { page = 1, limit = 20 } = req.query
      const offset = (page - 1) * limit

      // 获取书架小说列表
      const novels = await dbQuery(
        `
      SELECT 
        n.id, n.title, n.author, n.cover_url, n.category, n.status,
        n.chapter_count, n.word_count, n.rating, n.updated_at,
        ub.reading_progress, ub.is_favorite, ub.last_read_at,
        ub.last_read_chapter_id,
        c.title as last_chapter_title, c.chapter_number as last_chapter_number
      FROM user_bookshelf ub
      JOIN novels n ON ub.novel_id = n.id
      LEFT JOIN chapters c ON ub.last_read_chapter_id = c.id
      WHERE ub.user_id = ?
      ORDER BY ub.last_read_at DESC
      LIMIT ? OFFSET ?
    `,
        [req.user.id, parseInt(limit), offset]
      )

      // 获取总数
      const totalResult = await dbQuery(
        'SELECT COUNT(*) as total FROM user_bookshelf WHERE user_id = ?',
        [req.user.id]
      )

      const total = totalResult[0].total

      res.paginate(novels, parseInt(page), parseInt(limit), total)
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/bookshelf/{novelId}:
 *   post:
 *     summary: 添加小说到书架
 *     tags: [书架]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: novelId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 小说ID
 *     responses:
 *       200:
 *         description: 添加成功
 */
router.post(
  '/:novelId',
  [
    authenticateToken,
    param('novelId').isInt({ min: 1 }).withMessage('小说ID必须是正整数')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const novelId = req.params.novelId

      // 检查小说是否存在
      const novels = await dbQuery('SELECT id FROM novels WHERE id = ?', [
        novelId
      ])
      if (novels.length === 0) {
        return res.error('小说不存在', 'NOVEL_NOT_FOUND', 404)
      }

      // 添加到书架（如果已存在则忽略）
      await dbQuery(
        `
      INSERT INTO user_bookshelf (user_id, novel_id, added_at)
      VALUES (?, ?, NOW())
      ON DUPLICATE KEY UPDATE added_at = VALUES(added_at)
    `,
        [req.user.id, novelId]
      )

      res.success(null, '已添加到书架')
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/bookshelf/{novelId}:
 *   delete:
 *     summary: 从书架移除小说
 *     tags: [书架]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: novelId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 小说ID
 *     responses:
 *       200:
 *         description: 移除成功
 */
router.delete(
  '/:novelId',
  [
    authenticateToken,
    param('novelId').isInt({ min: 1 }).withMessage('小说ID必须是正整数')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const novelId = req.params.novelId

      // 从书架移除
      const result = await dbQuery(
        'DELETE FROM user_bookshelf WHERE user_id = ? AND novel_id = ?',
        [req.user.id, novelId]
      )

      if (result.affectedRows === 0) {
        return res.error('小说不在书架中', 'NOT_IN_BOOKSHELF', 404)
      }

      res.success(null, '已从书架移除')
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/bookshelf/{novelId}/favorite:
 *   put:
 *     summary: 切换小说收藏状态
 *     tags: [书架]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: novelId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 小说ID
 *     responses:
 *       200:
 *         description: 操作成功
 */
router.put(
  '/:novelId/favorite',
  [
    authenticateToken,
    param('novelId').isInt({ min: 1 }).withMessage('小说ID必须是正整数')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const novelId = req.params.novelId

      // 检查是否在书架中
      const bookshelfItems = await dbQuery(
        'SELECT is_favorite FROM user_bookshelf WHERE user_id = ? AND novel_id = ?',
        [req.user.id, novelId]
      )

      if (bookshelfItems.length === 0) {
        return res.error('请先将小说添加到书架', 'NOT_IN_BOOKSHELF', 404)
      }

      // 切换收藏状态
      const newFavoriteStatus = !bookshelfItems[0].is_favorite
      await dbQuery(
        'UPDATE user_bookshelf SET is_favorite = ? WHERE user_id = ? AND novel_id = ?',
        [newFavoriteStatus, req.user.id, novelId]
      )

      res.success(
        {
          isFavorite: newFavoriteStatus
        },
        newFavoriteStatus ? '已添加到收藏' : '已取消收藏'
      )
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/bookshelf/reading-history:
 *   get:
 *     summary: 获取阅读历史
 *     tags: [书架]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 20
 *         description: 每页数量
 *     responses:
 *       200:
 *         description: 获取成功
 */
router.get(
  '/reading-history',
  [
    authenticateToken,
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit')
      .optional()
      .isInt({ min: 1, max: 100 })
      .withMessage('每页数量必须在1-100之间')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const { page = 1, limit = 20 } = req.query
      const offset = (page - 1) * limit

      // 获取阅读历史
      const history = await dbQuery(
        `
      SELECT 
        rh.id, rh.reading_time, rh.created_at,
        n.id as novel_id, n.title as novel_title, n.author, n.cover_url,
        c.id as chapter_id, c.title as chapter_title, c.chapter_number
      FROM reading_history rh
      JOIN novels n ON rh.novel_id = n.id
      JOIN chapters c ON rh.chapter_id = c.id
      WHERE rh.user_id = ?
      ORDER BY rh.created_at DESC
      LIMIT ? OFFSET ?
    `,
        [req.user.id, parseInt(limit), offset]
      )

      // 获取总数
      const totalResult = await dbQuery(
        'SELECT COUNT(*) as total FROM reading_history WHERE user_id = ?',
        [req.user.id]
      )

      const total = totalResult[0].total

      res.paginate(history, parseInt(page), parseInt(limit), total)
    } catch (error) {
      next(error)
    }
  }
)

module.exports = router
